/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * SolicitaParametroUsuario.java
 *
 * Created on 05/03/2013, 03:01:02
 */
package com.bs.exibicao;

import com.bs.GestorRelatorios;
import com.bs.beans.ParametrosRelatorio;
import com.bs.beans.Relatorios;
import com.bs.persistencia.EntityManager;

import com.bs.util.Mensagens;
import java.awt.Component;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JPanel;

/**
 *
 * @author Bone
 */
public class SolicitaParametroUsuario extends javax.swing.JDialog {

    private static JPanel telaExibicao = null;
    public static final String PARAMETRO_PERIODO_REAL = "periodoReal";
    public static final String PARAMETRO_PERIODO_DATA = "periodoData";
    public static final String PARAMETRO_DATA = "data";
    public static final String PARAMETRO_INTEIRO = "inteiro";
    public static final String PARAMETRO_TEXTO_INTEIRO = "textoInteiro";
    public static final String PARAMETRO_PERIODO_INTEIRO = "periodoInteiro";
    public static final String PARAMETRO_SUGESTAO = "sugestao";
    private static HashMap<String, Relatorios> rels;
    private static String relatorioAtual = "";
    private static ArrayList<ParametrosRelatorio> parametros = new ArrayList<ParametrosRelatorio>();
    private static HashMap<String, Component> telasParametro = new HashMap<String, Component>();
    private EntityManager entityManager = new EntityManager();

    public static JPanel getTelaExibicao() {
        return telaExibicao;
    }

    public static void setTelaExibicao(JPanel telaExibicao) {
        SolicitaParametroUsuario.telaExibicao = telaExibicao;
    }

    /**
     * Creates new form SolicitaParametroUsuario
     */
    private SolicitaParametroUsuario(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    public SolicitaParametroUsuario() {
        initComponents();
        this.setModal(true);

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        textoLabel = new javax.swing.JLabel();
        jPTelaParametro = new javax.swing.JPanel();
        jBOk = new javax.swing.JButton();
        jBCancelar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setUndecorated(true);

        jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 51, 153)));

        textoLabel.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        textoLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        textoLabel.setText("Texto");

        jPTelaParametro.setMaximumSize(new java.awt.Dimension(460, 32767));
        jPTelaParametro.setMinimumSize(new java.awt.Dimension(42, 10));
        jPTelaParametro.setPreferredSize(new java.awt.Dimension(460, 200));
        jPTelaParametro.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        jBOk.setText("Ok");
        jBOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBOkActionPerformed(evt);
            }
        });

        jBCancelar.setText("Cancelar");
        jBCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPTelaParametro, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 532, Short.MAX_VALUE)
                    .addComponent(textoLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 532, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jBOk, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jBCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(textoLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPTelaParametro, javax.swing.GroupLayout.PREFERRED_SIZE, 8, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jBOk, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jBCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        setSize(new java.awt.Dimension(574, 133));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void jBCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBCancelarActionPerformed
        this.setVisible(false);
    }//GEN-LAST:event_jBCancelarActionPerformed

    private void jBOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBOkActionPerformed
        exibirRelatorio();
    }//GEN-LAST:event_jBOkActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBCancelar;
    private javax.swing.JButton jBOk;
    private static javax.swing.JPanel jPTelaParametro;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel textoLabel;
    // End of variables declaration//GEN-END:variables

    private static void parametrosDoRelatorio(ArrayList<ParametrosRelatorio> prs) {
        parametros.clear();
        parametros.addAll(prs);
        telasParametro.clear();
        jPTelaParametro.removeAll();
        for (ParametrosRelatorio p : prs) {
            if (p.getTipo().equals(PARAMETRO_DATA)) {
                telasParametro.put(p.getNomeParametro(), new ParametroData(p.getTexto()));
            }
            if (p.getTipo().equals(PARAMETRO_PERIODO_INTEIRO)) {
                telasParametro.put(p.getNomeParametro(), new ParametroPeriodoInteiro(p.getTexto()));
            }
            if (p.getTipo().equals(PARAMETRO_PERIODO_REAL)) {
                telasParametro.put(p.getNomeParametro(), new ParametroPeridodoReal(p.getTexto()));
            }
            if (p.getTipo().equals(PARAMETRO_PERIODO_DATA)) {
                telasParametro.put(p.getNomeParametro(), new ParametroPeriodoData(p.getTexto()));
            }
            if (p.getTipo().equals(PARAMETRO_INTEIRO)) {
                telasParametro.put(p.getNomeParametro(), new ParametroInteiro(p.getTexto()));
            }
            if (p.getTipo().equals(PARAMETRO_TEXTO_INTEIRO)) {
                telasParametro.put(p.getNomeParametro(), new ParametroTextoInteiro(p.getTexto()));
            }
            if (p.getTipo().equals(PARAMETRO_SUGESTAO)) {
                telasParametro.put(p.getNomeParametro(), new ParametroSugestao(
                        p.getTexto(), p.getConsulta(), p.getCampo(), p.getCampoRetorno()));
            }
            Component c = telasParametro.get(p.getNomeParametro());
            if (c instanceof IParametroPeriodo) {
                IParametroPeriodo prm = (IParametroPeriodo) c;
                prm.setParametro(p);
            }
            if (c instanceof IParametroValor) {
                IParametroValor prm = (IParametroValor) c;
                prm.setParametro(p);
            }
        }
        for (String k : telasParametro.keySet()) {
            Component c = telasParametro.get(k);
            c.setName(k);
            jPTelaParametro.add(k, c);
        }
    }

    @Override
    public void setVisible(boolean b) {
        if (b) {
            if (parametros.size() == 0) {
                exibirRelatorio();
                b = false;
            }
        }
        super.setVisible(b);
    }

    private static String getRelatorioAtual() {
        return relatorioAtual;
    }

    private static void setRelatorioAtual(String relatorioAtual) {
        SolicitaParametroUsuario.relatorioAtual = relatorioAtual;
    }

    private void setTexto(String texto) {
        textoLabel.setText(texto);
    }

    public static void exibeRelatorio(String nomeRelatorio) {
        try {

            if (rels == null) {
                rels = new HashMap<String, Relatorios>();
                Collection<Relatorios> col = new EntityManager().getCollection(Relatorios.class);
                for (Relatorios r : col) {
                    rels.put(r.getNome(), r);
                }
            }
            if (rels.containsKey(nomeRelatorio)) {
                SolicitaParametroUsuario s = new SolicitaParametroUsuario();
                setRelatorioAtual(nomeRelatorio);
                Relatorios r = rels.get(nomeRelatorio);
                s.setTexto(r.getDescricao());
                parametrosDoRelatorio(new ArrayList<ParametrosRelatorio>(r.getParametrosRelatorioList()));
                s.setSize(new Dimension(s.getWidth(), s.getHeight() + r.getParametrosRelatorioList().size() * 45));
                s.validate();
                s.repaint();
                s.setVisible(true);
            } else {
                Mensagens.exibeMensagemAlerta("Relatório inexistente");
            }
        } catch (Exception ex) {
            Mensagens.exibeMensagemInformativa("Erro ao exibir relatório.\n" + ex.getMessage());
        }
    }

    private void exibirRelatorio() {
        HashMap<String, Object> params = new HashMap<String, Object>();
        for (Component c : jPTelaParametro.getComponents()) {
            if (c instanceof IParametroPeriodo) {
                IParametroPeriodo per = (IParametroPeriodo) c;
                for (String s : per.parametros().keySet()) {
                    params.put(s, per.parametros().get(s));
                }
            }
            if (c instanceof IParametroValor) {
                IParametroValor per = (IParametroValor) c;
                for (String s : per.parametros().keySet()) {
                    params.put(s, per.parametros().get(s));
                }
            }
        }
        GestorRelatorios g = new GestorRelatorios();
        try {
            if (telaExibicao == null) {
                g.exibirRelatorio(relatorioAtual, params, entityManager.getConnection());
            } else {
                g.exibirRelatorio(relatorioAtual, params, entityManager.getConnection(), telaExibicao);
            }

            setVisible(false);
        } catch (Exception ex) {
            Logger.getLogger(SolicitaParametroUsuario.class.getName()).log(Level.SEVERE, null, ex);
        }
        g = null;
    }
}
